<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
      <el-form-item label="设备名称" prop="dev_name">
        <el-input v-model.trim="queryParams.dev_name" placeholder="请输入设备名称" clearable style="width: 240px"
          @keyup.enter="handleQuery" @clear="handleQuery" @input="handleInput" />
      </el-form-item>
      <el-form-item label="设备编码" prop="dev_code">
        <el-input v-model.trim="queryParams.dev_code" placeholder="请输入设备编码" clearable style="width: 240px"
          @keyup.enter="handleQuery" @clear="handleQuery" @input="handleInput" />
      </el-form-item>
      <el-form-item label="所属企业" prop="ent_id" label-width="100px">
        <el-select v-model="queryParams.ent_id" clearable placeholder="请选择所属企业" @change="handleQuery"
          style="width: 240px">
          <el-option v-for="item in options1" :key="item.id" :label="item.entName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="在线状态" prop="online_status">
        <el-select v-model="queryParams.online_status" clearable placeholder="请选择在线状态" @change="handleQuery"
          style="width: 220px">
          <el-option v-for="item in options2_2" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Upload" @click="handleImport">导入数据</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>
    <!-- 表格数据 -->
    <el-table v-loading="loading" size="large" :max-height="tableHeight" :data="dataList">
      <el-table-column type="index" label="序号" width="120" align="center">
        <template #default="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备名称" v-if="columns[0].visible" align="center" width="150">
        <template #default="scope">
          <span :class="{ 'online': scope.row.online_status === 1, 'offline': scope.row.online_status === 0 }">
            {{ scope.row.dev_name }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="设备编码" v-if="columns[1].visible" align="center" width="200">
        <template #default="scope">
          <span :class="{ 'online': scope.row.online_status === 1, 'offline': scope.row.online_status === 0 }">
            {{ scope.row.dev_code }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="物联卡号" v-if="columns[2].visible" prop="phone_num" align="center" width="150" />
      <el-table-column label="所属公司" v-if="columns[3].visible" prop="ent_name" align="center" width="250" />
      <el-table-column label="所属监测站" v-if="columns[4].visible" prop="station_Name" align="center" width="200" />
      <el-table-column label="所属线路" v-if="columns[5].visible" prop="line_name" align="center" width="200" />
      <el-table-column label="在线状态" v-if="columns[6].visible" align="center" width="100">
        <template #default="scope">
          <!-- 动态绑定类名 -->
          <span :class="{ 'online': scope.row.online_status === 1, 'offline': scope.row.online_status === 0 }">
            {{ scope.row.online_status === 1 ? '在线' : '离线' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="是否报警" v-if="columns[7].visible" align="center" width="200">
        <template #default="scope">
          <span>{{ scope.row.offline_alarm_flag==1?'是':'否' }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" min-width="420px" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Setting" @click="handleSys(scope.row)">设备配置</el-button>
          <el-button link type="success" icon="Refresh" @click="handleDelete2(scope.row)">固件更新</el-button>
          <el-button link type="warning" icon="Bell" @click="handleAlarm(scope.row)">告警信息</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 告警类型选择对话框 -->
    <el-dialog :title="`“${currentRow?.dev_code}” 设备告警类型选择`"  v-model="openAlarmDialog" width="400px"  append-to-body class="alarm-select-dialog">
      <div class="dialog-content">
        <!-- 增大按钮尺寸为 large -->
        <el-button type="primary" size="large" round @click="handleAlarmType('grounding')">
          接地告警
        </el-button>
        <el-button type="warning" size="large" round @click="handleAlarmType('voltage')">
          电压告警
        </el-button>
      </div>
      <template #footer>
      </template>
    </el-dialog>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属企业" prop="ent_id">
          <el-select v-model="form.ent_id" placeholder="请选择所属企业" @change="handleEntChange">
            <el-option v-for="item in options1" :key="item.id" :label="item.entName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属监测站" prop="station_id" v-if="form.ent_id">
          <el-select v-model="form.station_id" placeholder="请选择监测站" @change="handleEntChange2">
            <el-option v-for="item in options2" :key="item.id" :label="item.station_Name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属线路" prop="line_code" v-if="form.station_id">
          <el-cascader style="width: 600px;" ref="cascaderRef" @change="handleCascaderChange" v-model="form.line_code"
            :options="options3"
            :props="{ checkStrictly: true,children:'branch_Lines',label:'line_name',value:'line_code'}" />
        </el-form-item>
        <el-form-item label="设备名称" prop="dev_name">
          <el-input v-model.trim="form.dev_name" maxlength="30" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备编码" prop="dev_code">
          <el-input v-model.trim="form.dev_code" maxlength="30" placeholder="请输入设备编码" />
        </el-form-item>
        <el-form-item label="物联卡号" prop="phone_num">
          <el-input v-model.trim="form.phone_num" maxlength="50" placeholder="请输入物联卡号" />
        </el-form-item>
        <el-form-item label="离线是否报警" label-width="130">
          <el-radio-group v-model="form.offline_alarm_flag">
            <el-radio :value="0">不报警</el-radio>
            <el-radio :value="1">报警</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="报警时间间隔" label-width="130" v-if="form.offline_alarm_flag==1">
          <el-select v-model="form.offline_alarm_time" placeholder="请选择时间间隔" style="width: 240px">
            <el-option v-for="item in options4" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title2" v-model="open2" width="800px" append-to-body :close-on-click-modal="false">
      <el-form ref="roleRef2" :model="form2" :rules="rules2" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="固件版本号" prop="version">
              <el-input v-model.trim="form2.version" disabled maxlength="30" placeholder="" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="服务器IP" prop="ip">
              <el-input v-model.trim="form2.ip" maxlength="30" placeholder="请输入服务器IP" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务器端口号" prop="port">
              <el-input v-model.trim="form2.port" maxlength="30" placeholder="请输入服务器端口号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="波特率" prop="baudRate">
              <el-input v-model.trim="form2.baudRate" maxlength="30" placeholder="请输入波特率" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="485地址" prop="addr485">
              <el-input v-model.trim="form2.addr485" maxlength="30" placeholder="请输入485地址" />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="过压门限" prop="ratedvoltage">
              <el-input v-model.trim="form2.ratedvoltage" maxlength="30" placeholder="请输入额定电压" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="欠压门限" prop="scalefactor">
              <el-input v-model.trim="form2.scalefactor" maxlength="30" placeholder="请输入比例系数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电压变比" prop="pt">
              <el-input v-model.trim="form2.pt" maxlength="30" placeholder="请输入电压变比" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电流变比" prop="ct">
              <el-input v-model.trim="form2.ct" maxlength="30" placeholder="请输入电流变比" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="零序电流" prop="leakagecurrent">
              <el-input v-model.trim="form2.leakagecurrent" maxlength="30" placeholder="请输入零序电流" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="零序电流变比" prop="shortcircuitcurrent">
              <el-input v-model.trim="form2.shortcircuitcurrent" maxlength="30" placeholder="请输入零序电流变比" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="3U0电压门限" prop="cabinet">
              <el-input v-model.trim="form2.cabinet" maxlength="30" placeholder="请输入3U0电压门限" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="进入休眠时间 (秒)" prop="screenidle" label-width="150">
              <el-input v-model.trim="form2.screenidle" maxlength="30" placeholder="请输入进入休眠时间" />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="密码" prop="pwd">
              <el-input v-model.trim="form2.pwd" type="number" maxlength="8" placeholder="请输入密码" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="" prop="screenidle" label-width="30" v-if="Sensers">
              <span @click="toList(form2)"
                style="color: #409eff;font-size: 14px;display: flex;align-items: center;">查看传感器列表 <el-icon>
                  <DArrowRight />
                </el-icon></span>
            </el-form-item>
            <el-form-item label="" prop="screenidle" label-width="30" v-else>
              <span style="color: #999;font-size: 14px;display: flex;align-items: center;">查看传感器列表 <el-icon>
                  <DArrowRight />
                </el-icon></span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" style="float: left;margin:0 0 10px 30px;" :disabled="disabled"
            @click="submitForm3">发送配置信息</el-button>
          <el-button type="warning" style="float: left;margin:0 0 10px 40px;" :disabled="disabled"
            @click="submitForm4">发送点表信息</el-button>
          <el-button type="primary" :disabled="disabled" @click="submitForm2">确 定</el-button>
          <el-button @click="open2=false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="roleRef3" :model="form3" :rules="rules3" label-width="120px">
        <el-form-item label="所属企业" prop="ent_id">
          <el-select v-model="form3.ent_id" placeholder="请选择所属企业" @change="handleEntChange">
            <el-option v-for="item in options1" :key="item.id" :label="item.entName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属监测站" prop="station_id" v-if="form3.ent_id">
          <el-select v-model="form3.station_id" placeholder="请选择监测站" @change="handleEntChange2">
            <el-option v-for="item in options2" :key="item.id" :label="item.station_Name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-upload ref="uploadRef" prop="guid" v-if="form3.station_id" :limit="1" accept=".xlsx, .xls"
          :headers="upload.headers" :action="upload.url" :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="true" drag>
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" link style="float: left; margin: 0 0 10px 30px;" @click="handleDownloadTemplate">
            <el-icon>
              <Download />
            </el-icon>点击下载导入模板
          </el-button>
          <div>
            <el-button type="primary" @click="submitFileForm">确 定</el-button>
            <el-button @click="upload.open = false">取 消</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getToken } from "@/utils/auth";
import { useInfoStore } from '@/store/modules/info.js'
const userInfo = useInfoStore();

const router = useRouter();
const { proxy } = getCurrentInstance();
// const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
const tableHeight = ref(document.documentElement.scrollHeight - 280 + "px");


const dataList = ref([]);
const open = ref(false);
const open2 = ref(false);
const loading = ref(false);
const disabled = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const title2 = ref("");
const dateRange = ref([]);
const menuOptions = ref([]);
const deptOptions = ref([]);
const menuRef = ref(null);
const options1 = ref([]);
const options2 = ref([]); //监测站点
const options3 = ref([]); //线路列表
const cascaderRef = ref(null);
const options4 = [
  { value: 1, label: '1分钟' },
  { value: 2, label: '2分钟' },
  { value: 5, label: '5分钟' },
  { value: 10, label: '10分钟' },
  { value: 30, label: '30分钟' },
]
const Dev_id = ref(null);
const options2_2 = ref([
  { id: 1, name: '在线' },
  { id: 0, name: '离线' },
]);
const Sensers = ref(null);
// 列显隐信息
const columns = ref([
  { key: 1, label: `设备名称`, visible: false },
  { key: 2, label: `设备编码`, visible: true },
  { key: 3, label: `物联卡号`, visible: false },
  { key: 4, label: `所属公司`, visible: true },
  { key: 5, label: `所属监测站`, visible: true },
  { key: 6, label: `所属线路`, visible: true },
  { key: 7, label: `在线状态`, visible: true },
  { key: 8, label: `是否报警`, visible: false },
])
const openAlarmDialog = ref(false); // 告警选择对话框显示控制
const currentRow = ref(null); // 当前操作的设备行数据
const data = reactive({
  form: {
    id: null,
    ent_id: null,//企业ID
    dev_name: null,//设备名称
    dev_code: null,//设备编码
    phone_num: null,//设备编码
    offline_alarm_flag: 0,//离线是否报警 0-不报警；1-报警
    offline_alarm_time: 5,//设备编码
    station_id:null,//监测站ID
    line_id:null,//线路ID
    line_code:null,//线路编码
    line_type:0,//线路类型 0-母线；1-支线
    state: 1,//是否停用
  },
  form2: {
    version: null,//固件版本号
    id: null,//设备ID
    dev_ID: null,//设备ID
    dev_code: null,//设备编码
    cid: null,//设备编号
    pwd: null,//设备密码
    ip: null,//服务器IP
    port: null,// 服务器端口号
    baudRate: null,// 波特率
    addr485: null,// 485地址
    ratedvoltage: null,// 过压门限
    scalefactor: null,// 欠压门限
    pt: null,// 电压变比
    ct: null,// 电流变比
    leakagecurrent: null,// 漏电电流
    shortcircuitcurrent: null,// 零序电流变比
    cabinet: null,// 3U0电压门限
    screenidle:null, //休眠时间
  },
  form3:{
    ent_id: null,//企业ID 
    station_id: null,//监测站点ID
  },
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    ent_id: null,//企业ID
    station_id: null,//监测站点ID
    dev_model: null,//设备型号
    dev_code: null,//设备编码
    dev_name: null,//设备名称
    state: 1,//是否停用
    online_status: null,//在线状态
  },
  rules: {
    ent_id: [{ required: true, message: "所属企业不能为空", trigger: "blur" }],
    dev_name: [{ required: true, message: "设备名称不能为空", trigger: "blur" }],
    dev_code: [{ required: true, message: "设备编码不能为空", trigger: "blur" }],
    station_id: [{ required: true, message: "请选择监测站", trigger: "blur" }],
    line_code: [{ required: true, message: "请选择线路", trigger: "blur" }],
  },
  rules2: {
    pwd: [{ required: true, message: "设备密码不能为空", trigger: "blur" }],
    ip: [{ required: true, message: "服务器IP不能为空", trigger: "blur" }],
    port: [{ required: true, message: "服务器端口号不能为空", trigger: "blur" }],
    baudRate: [{ required: true, message: "波特率不能为空", trigger: "blur" }],
    addr485: [{ required: true, message: "485地址不能为空", trigger: "blur" }],
    ratedvoltage: [{ required: true, message: "过压门限不能为空", trigger: "blur" }],
    scalefactor: [{ required: true, message: "欠压门限不能为空", trigger: "blur" }],
    pt: [{ required: true, message: "电压变比不能为空", trigger: "blur" }],
    ct: [{ required: true, message: "电流变比不能为空", trigger: "blur" }],
    leakagecurrent: [{ required: true, message: "零序电流不能为空", trigger: "blur" }],
    shortcircuitcurrent: [{ required: true, message: "零序电流变比不能为空", trigger: "blur" }],
    cabinet: [{ required: true, message: "3U0电压门限不能为空", trigger: "blur" }],
  },
  rules3: {
    ent_id: [{ required: true, message: "请选择所属企业", trigger: "blur" }],
    station_id: [{ required: true, message: "请选择监测站", trigger: "blur" }],
  },
});
// 文件ID
const filedata = ref(null);
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/api/YDWS_Dev_Senser/UploadSenserExcel"
});

const { queryParams, form, form2, form3, rules ,rules2 , rules3} = toRefs(data);

// 自定义校验函数
const validateTypeOrSpec = (rule, value, callback) => {
  if (!form.value.types && !form.value.specifications) {
    callback(new Error('型号和规格至少输入一项'));
  } else {
    callback();
  }
};
// 更新校验规则
rules.value.types = { validator: validateTypeOrSpec, trigger: 'blur' };
rules.value.specifications = { validator: validateTypeOrSpec, trigger: 'blur' };
// 跳转至传感器列表
function toList(form2) {
  router.push({
    path: "/cloudTv/device/sensorList",
    query: {
      dev_code: form2.dev_code,
    },
  });
}
/** 查询企业列表下拉 */
function getGetEnterpriseList() {
  proxy.cloudTv_API.GetEnterpriseList({}).then(response => {
    if (response.data) {
      options1.value = response.data || [];
    }
  });
}
// 打开告警类型选择对话框
function handleAlarm(row) {
  currentRow.value = row;
  openAlarmDialog.value = true;
}

// 处理告警类型选择
function handleAlarmType(type) {
  openAlarmDialog.value = false;
  router.push({
    path: `/cloudTv/warning/${type}`, // 假设路由路径为/cloudTv/alarm/groundingList 或 /cloudTv/alarm/voltageList
    query: {
      dev_code: currentRow.value.dev_code,
    }
  });
}
//获取监测站
function handleEntChange(value) {
  // console.log(options1.value);
  proxy.cloudTv_API.GetStationList({
    enterpriseID: value,
  }).then(response => {
    if (response.data?.length > 0) {
      options2.value = response.data || [];
      options2.value.forEach(item => {
        item.station_Name = item.staName;
      });
      if(!form.value.station_id){ //如果监测站无值，则默认第一条
         form.value.station_id = options2.value[0].id;
      }
      getLineList(form.value.station_id);
    }else{
      form.value.station_id = null;
      options2.value =  [];
      form.value.line_code = null;
      options3.value =  []; 
      form3.value.station_id = null;
      proxy.$modal.msgError("当前企业还没有添加监测站~");
    }
  });
}

//获取监测--母线-支线
function getLineList(value) {
  proxy.cloudTv_API.GetMasterLineList({
    stationID: value,
    state: 1,
  }).then(response => {
    if (response.data?.length > 0) {
      options3.value = response.data || [];
      if(!form.value.line_code){ //如果线路无值，则默认第一条
        form.value.line_code = options3.value[0].line_code;
        form.value.line_id = options3.value[0].id;
      }
    }else{
      form.value.line_code = null;
      form.value.line_id = null;
      options3.value =  [];
      proxy.$modal.msgError("当前监测站还没有线路~");
    }
  });
}

function handleEntChange2(value) {
  form.value.line_code = null;//选中监测站 清空支线
  form.value.line_id = null;
  getLineList(value);
}
  // 主动关闭弹层
function handleCascaderChange(e) {
    // 获取当前选中的节点列表
    const item = cascaderRef.value.getCheckedNodes()[0].data;
    form.value.line_type = item?.master_LineID?1:0;
    form.value.line_id = item.id;
    cascaderRef.value.togglePopperVisible(false)
}
/** 查询列表 */
function getList() {
  loading.value = true;
  proxy.cloudTv_API.GetDevicePageList(queryParams.value).then(response => {
    dataList.value = response.data.list;
    total.value = response.data.total;
    loading.value = false;
  });
}
// 输入时触发的防抖处理函数
let timer = null;
function handleInput() {
  clearTimeout(timer);
  timer = setTimeout(handleQuery, 300);
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNo = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除设备名称"' + row.dev_name + '"的数据项?').then(function () {
    proxy.cloudTv_API.DelDevice({
        id: row.id,
      }).then(response => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      });
  })
}
/** 固件升级 */
function handleDelete2(row) {
  proxy.cloudTv_API.CheckFireWare({
    id: row.id,
  }).then(response => {
      if (response.data) {
        proxy.$modal.confirm(`当前设备名称"${row.dev_name}", 固件可升级到版本号：${response.message}, 是否确定更新?`).then(function () {
           proxy.cloudTv_API.SendFireWareToDevice(response.data).then(response => {
                proxy.$modal.msgSuccess(response.message);
            });   
        })
      }else{
        proxy.$modal.msgWarning(response.message);
      }
  });    

}
  /** 导入按钮操作 */
  function handleImport() {
    upload.title = "导入文件信息";
    upload.open = true;
  };

  /** 下载模板操作 */
  function handleDownloadTemplate() {
      const link = document.createElement('a');
      link.href = import.meta.env.VITE_APP_BASE_API + "/Exchange/ExcelTemplate/Template.xls";
      console.log(link.href);
      link.setAttribute('download', `导入设备模版_${new Date().getTime()}.xls`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
  };

  /**文件上传中处理 */
  const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true;
  };

  /** 文件上传成功处理 */
  const handleFileSuccess = (response, file, fileList) => {
    upload.isUploading = false;
    if (response.code == 1) {
      filedata.value = response.data;
      proxy.$modal.msgSuccess("上传成功");
    } else {
      proxy.$modal.msgError(response.message);
      proxy.$refs["uploadRef"].handleRemove(file);
    }
  };

  /** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["roleRef3"].validate(valid => {
    if (valid) {
      if (filedata.value) {
        proxy.cloudTv_API.AddDevAndSen({
             GUID: filedata.value,
             StaID: form3.value.station_id,
          }).then(response => {
              // 清空表单数据
            upload.open = false;
            form3.value = {
              ent_id: null,
              station_id: null,
            };
            filedata.value = null;
            proxy.$refs["uploadRef"].clearFiles();
            getList();
            proxy.$modal.msgSuccess("导入成功");
          });
      } else {
        proxy.$modal.msgError("请等待文件上传完成");
      }
    }
  });
};

/** 重置新增的表单以及其他数据  */
function reset() {
  if (menuRef.value != undefined) {
    menuRef.value.setCheckedKeys([]);
  }
  form.value = {
    id: null,
    ent_id: null,//企业ID
    dev_name: null,//设备名称
    dev_code: null,//设备编码
    phone_num: null,//设备编码
    offline_alarm_flag: 0,//离线是否报警 0-不报警；1-报警
    offline_alarm_time: 5,//离线报警时间间隔，单位分钟，默认0为无间隔
    station_id:null,//监测站ID
    line_id:null,//线路ID
    line_type:0,//线路类型 0-母线；1-支线
    line_code:null,//线路编码
    state: 1,//是否停用
  };
}
/** 新增物料 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增设备";
}

/** 修改 */
function handleUpdate(row) {
  let newRow = JSON.parse(JSON.stringify(row));
  reset();
  Object.keys(form.value).forEach(key => {
    form.value[key] = newRow[key];
  });
  open.value = true;
  title.value = "修改设备";
  handleEntChange(newRow.ent_id);//获取监测站
}

// 设备配置
function handleSys(row) {
  Dev_id.value = row.id;
  Sensers.value = row?.sensers?.length || 0;
  proxy.cloudTv_API.GetDevCFG({
    id: row.id,
  }).then(res => {
    const data = res.data;
    Object.keys(form2.value).forEach(key => {
      form2.value[key] = data[key];
    });
    form2.value.dev_code = row.dev_code;
    open2.value = true;
    title2.value = `设备配置 - ${form2.value.cid}`;
    if(data.id==0){
      setTimeout(() => {
        proxy.$modal.msgWarning({
          message: "当前设备还没有配置信息~",
          duration: 1000 
        });
      }, 100);
      disabled.value = true;
    }else{
      disabled.value = false;
    }
  });
}
  
/** 提交按钮 */
function submitForm() {
  proxy.$refs["roleRef"].validate(valid => {
    if (valid) {
      if (form.value.id) {
        proxy.cloudTv_API.EditDevice({
          ...form.value,
        }).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        proxy.cloudTv_API.AddDevice({
          ...form.value,
        }).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 提交按钮 */
function submitForm2() {
  proxy.$refs["roleRef2"].validate(valid => {
    if (valid) {
      proxy.cloudTv_API.UpDateDevCFG({
        ...form2.value,
      }).then(response => {
        proxy.$modal.msgSuccess("修改成功");
      });
    }
  });
}
/** 发送配置信息给设备 */
function submitForm3() {
  proxy.cloudTv_API.GetSendConfigToDevice({
   id: Dev_id.value,
  }).then(response => {
    proxy.$modal.msgSuccess("发送成功");
    open2.value = false;
  });
}
/** 发送电表给设备 */
function submitForm4() {
  proxy.cloudTv_API.GetCanlistConfigToDevice({
   id: Dev_id.value,
  }).then(res => {
    proxy.$modal.msgSuccess(res.message);
    open2.value = false;
  });
}
// 复制
async function copy(text) {
  console.log(text);
  try {
    await navigator.clipboard.writeText(text);
    proxy.$modal.msgSuccess('复制成功');
  } catch (err) {
    console.log(err);

  }
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

getGetEnterpriseList();
getList();
    

</script>

<style lang="scss" scoped>
.el-input-number {
  width: 190px;
}

.required-star {
  color: #F56C6C;
  margin-right: 4px;
}
.online {
  color: #67C23A;
}

.offline {
  color: #F56C6C;
}

/* 告警选择对话框样式优化 */
.dialog-content {
  // 调整为垂直方向布局
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;  /* 使用flex gap代替margin */
  .el-button{
    width: 200px;
  }
}
:deep(.alarm-select-dialog) {
  .el-dialog__header {
    padding: 16px 24px;
    background: #f8f9fc;
    border-bottom: 1px solid #ebedf0;
    .el-dialog__title {
      font-size: 16px;
      font-weight: 500;
      color: #2c3e50;
    }
  }
  
  .el-dialog__body {
    padding: 32px 24px;
  }

  .el-dialog__footer {
    padding: 0 24px 24px;
    .el-button {
      font-size: 14px;
      color: #606266;
    }
  }

  /* 按钮悬停效果优化 */
  .el-button--primary {
    &:hover {
      opacity: 0.9;
      transform: translateY(-1px);
      transition: all 0.2s;
    }
  }
  .el-button--warning {
    &:hover {
      opacity: 0.9;
      transform: translateY(-1px);
      transition: all 0.2s;
    }
  }
}
</style>